package com.aisino.order.service.impl;

import com.aisino.order.client.ProductClient;
import com.aisino.order.dataobject.OrderDetail;
import com.aisino.order.dataobject.OrderMaster;
import com.aisino.order.dataobject.ProductInfo;
import com.aisino.order.dto.CartDTO;
import com.aisino.order.dto.OrderDTO;
import com.aisino.order.enums.OrderStatus;
import com.aisino.order.enums.PayStatusEnum;
import com.aisino.order.repository.OrderMasterRepository;
import com.aisino.order.service.OrderService;
import com.aisino.order.utils.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private ProductClient productClient;

    @Override
    public OrderDTO create(OrderDTO orderDTO) {

        String orderId = KeyUtil.getUniqueKey();

        List<String> productIdList = orderDTO.getOrderDetailList().stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());
        List<ProductInfo> productInfoList = productClient.listForOrder(productIdList);

        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            for (ProductInfo productInfo : productInfoList){
                    if (productInfo.getProductId().equals(orderDetail.getProductId())){
                            orderAmount = productInfo.getProductPrice()
                                            .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                                            .add(orderAmount);
                            BeanUtils.copyProperties(productInfo,orderDetail);
                            orderDetail.setOrderId(orderId);
                            orderDetail.setDetailId(KeyUtil.getUniqueKey());
                    }
            }
        }

        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());

        productClient.decreaseStock(cartDTOList);

        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatus.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);
        return orderDTO;
    }
}
